# -*- coding:utf-8 -*-
"""
Created on 11 sep 2011

@author: Olof Manbo
"""

import httplib
import urllib
import test_pb2

import requests
import random
import xml.parsers.expat
import matplotlib.pyplot as plt
header = {"Content-Type": "application/x-www-form-urlencoded"}

#conn = httplib.HTTPConnection("sveanas.appspot.com")
conn = httplib.HTTPConnection("localhost:8888")

def sendProcessRequest(type, argument):
    processRequest = test_pb2.ProcessRequest()
    processRequest.command = type
    processRequest.argument = argument
    
    
    
    params = processRequest.SerializeToString()
    conn.request("POST", "/simulatorwebservice/api/proto/process", params , header)
    r1 = conn.getresponse()
#    print r1.status, r1.reason
    data1 = r1.read()
    conn.close()
#    print data1
    
    processResponse = test_pb2.ProcessResponse()
    
    processResponse.ParseFromString(data1)
#    print processResponse.success

def hex2slong(value):
    return int(value, 16) - 0x100000000*(int(value, 16) > 0x7fffffff)

conn.request("GET", "http://localhost:8888/simulatorwebservice/api/resources.xml")
r1 = conn.getresponse()
print r1.status, r1.reason
xmldata = r1.read()
conn.close()
print xmldata

stuff = {}

# 3 handler functions
def start_element(name, attrs):
    global stuff
    print 'Start element:', name, attrs
    if name == 'resource':
        stuff[hex2slong(attrs["key"])] = attrs['name']
def end_element(name):
    print 'End element:', name
def char_data(data):
    print 'Character data:', repr(data)

p = xml.parsers.expat.ParserCreate()

p.StartElementHandler = start_element
p.EndElementHandler = end_element
p.CharacterDataHandler = char_data

p.Parse(xmldata, 1)
print stuff


rabbits_list = []
foxes_list = []
carrots_list = []
for n in range(100):
    nodeResponse = requests.sendNodeRequest("localhost:8888")
    
    
    rabbits = 0
    foxes = 0
    carrots = 0
    for node in nodeResponse.node:
        #print node.resource_key, node.x, node.y
        #print stuff[node.resource_key], node.x, node.y
        rabbits += 1*stuff[node.resource_key] == "rabbits"
        foxes += 1*stuff[node.resource_key] == "foxes"
        carrots += 1*stuff[node.resource_key] == "carrots"
            
    print "Rabbits: %i "%rabbits,
    print "Foxes: %i"%foxes,
    print "Carrots: %i"%carrots,
    print "Turn: %i"%n
    rabbits_list.append(rabbits)
    foxes_list.append(foxes)
    carrots_list.append(carrots)
    sendProcessRequest(test_pb2.ProcessRequest.RUN, "Run")

conn.close()
plt.plot(rabbits_list)
plt.plot(foxes_list)
plt.plot(carrots_list)

plt.figure()
plt.subplot(221)
plt.plot(rabbits_list, foxes_list)
plt.subplot(222)
plt.plot(rabbits_list, carrots_list)
plt.subplot(223)
plt.plot(carrots_list, foxes_list)

plt.show()